package com.yun.blog.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author : simple
 * @title : SpringUtils
 * @projectName : dantouBlog-back
 * @description : TODO
 * @email : yun_simple@163.com
 * @date : 2023/6/17下午12:57
 */

@Component
public class SpringUtils implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtils.context = applicationContext;
    }

    /**
     * 获取当前的环境配置，无配置返回null
     *
     * @return String[] 当前的环境配置
     * @author yun
     * @date 2023/6/17 下午1:02
     */
    public static String[] getActiveProfiles() {
        return context.getEnvironment().getActiveProfiles();
    }

    /**
     * 获取当前运行环境
     * @return String 获取当前运行环境
     * @author yun
     * @date 2023/6/17 下午1:05
     */
    public static String getActiveProfile() {
        String[] activeProfiles = getActiveProfiles();
        if (activeProfiles.length > 0) {
            return activeProfiles[0];
        } else {
            return null;
        }
    }

    /**
     * 通过名称获取bean
     * <p> @SuppressWarnings("unchecked") 忽略未检查的类型转换</p>
     * @author yun
     * @date 2023/6/17 下午1:21
     * @param name bean name
     * @return T
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name){
        return (T) context.getBean(name);
    }

    /**
     * 通过类型获取bean
     * @author yun
     * @date 2023/6/17 下午1:21
     * @param clazz bean类型
     * @return T
     */
    public static <T> T getBean(Class<T> clazz){
        return context.getBean(clazz);
    }

}
